package com.cloud.business.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Description: mybatis-plus公共字段自动填充
 **/
@Component
public class MybatisMetaObjectHandlerConfig implements MetaObjectHandler {

    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private Object defaultDeleted;

    @Override
    public void insertFill(MetaObject metaObject) {
        // TODO 根据业务补充创建人等
        Object createdTime = this.getFieldValByName("createdTime", metaObject);
        Object delFlag = this.getFieldValByName("delFlag", metaObject);
        if(ObjectUtil.isNotNull(createdTime)){
            this.setFieldValByName("createTime", new Date(), metaObject);
        }
        if(ObjectUtil.isNotNull(delFlag)){
            setFieldValByName("delFlag", defaultDeleted, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if(ObjectUtil.isNotNull(updateTime)){
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
}
